require "import"
import "android.os.Handler"
import "android.widget.LinearLayout"
import "android.widget.SeekBar"
import "android.widget.TextView"
import "android.widget.Button"
import "android.widget.ImageView"
import "android.widget.ListView"
import "android.view.View"
import "android.media.MediaPlayer"
import "android.content.DialogInterface"
import "android.view.WindowManager"
import "android.content.Intent"
import "android.provider.Settings"
import "android.content.pm.PackageManager"
import "android.content.Context"
import "android.os.Build"
import "android.os.VibrationEffect"
import "android.os.Vibrator"
import "android.widget.Toast"
import "java.io.File"
import "java.lang.String"
import "java.io.FileReader"
import "java.io.FileWriter"
import "java.util.ArrayList"
import "android.view.KeyEvent"
import "java.io.BufferedWriter"
import "java.io.BufferedReader"
import "android.graphics.Color"
import "android.widget.EditText"
import "android.app.AlertDialog"
import "android.app.ProgressDialog"
import "android.graphics.drawable.ColorDrawable"
import "android.widget.Spinner"
import "android.widget.PageView"
import "android.widget.CardView"
import "android.widget.ArrayAdapter"
import "android.widget.RippleLayout"
import "android.widget.RelativeLayout"
import "android.media.AudioManager"
import "android.provider.MediaStore"
import "java.io.FileOutputStream"
import "java.io.OutputStreamWriter"
import "java.io.InputStreamReader"
import "java.io.FileInputStream"
import "java.text.SimpleDateFormat"
import "java.util.Date"
import "android.content.ContentValues"
import "android.media.MediaMuxer"
import "android.media.MediaFormat"
import "android.content.*"
import "android.net.Uri"
import "android.widget.*"
import "java.lang.reflect.Array"
import "java.lang.System"
import "android.os.Environment"
import "com.androlua.*"

context = activity or service
vibrator = context.getSystemService(Context.VIBRATOR_SERVICE)
vibrator.vibrate(100)

if isPlaying then
    mediaPlayer.stop()
    mediaPlayer.reset()
    isPlaying = false
    currentSoundFilePath = nil
end

-- Variável global para armazenar a posição da pista atual
currentSoundIndex = 0
folderPath = "/storage/emulated/0/Grabación con Plugin"
folder = File(folderPath)
if not folder.exists() then
    success = folder.mkdirs()
    if success then
        service.asyncSpeak("Criado por Sergio Pina: " .. folderPath)
    else
        service.asyncSpeak("Não foi possível criar a pasta em: " .. folderPath)
    end
end
externalPath = Environment.getExternalStorageDirectory().getAbsolutePath() -- Corrigido de externalqrstPath para externalPath
soundFolderPath = externalPath .. "/Grabación con Plugin/"
soundFolder = File(soundFolderPath)
soundFiles = soundFolder.listFiles()
soundFilePaths = {}

if soundFiles ~= nil then
    soundFileCount = Array.getLength(soundFiles)

    if soundFileCount > 0 then
        soundFileCreationTimes = {}
        for i = 0, soundFileCount - 1 do
            soundFile = soundFiles[i]
            soundFilePath = soundFile.getAbsolutePath()

            fileName = soundFile.getName()
            creationTime = soundFile.lastModified()

            table.insert(soundFileCreationTimes, { filePath = soundFilePath, displayName = fileName, creationTime = creationTime })
        end

        table.sort(soundFileCreationTimes, function(a, b)
            return a.creationTime < b.creationTime
        end)

        for i = 1, #soundFileCreationTimes do
            soundFile = soundFileCreationTimes[i]
            table.insert(soundFilePaths, { filePath = soundFile.filePath, displayName = soundFile.displayName })
        end
    else
        service.asyncSpeak("Não foram encontrados arquivos de som na pasta: " .. soundFolderPath)
        return false
    end
else
    service.asyncSpeak("Não foi possível acessar a pasta: " .. soundFolderPath)
    return false
end

adapterItems = {}
isLongPress = false

mediaPlayer = MediaPlayer()

function cargarArchivos()
    soundFilePaths = {}
    soundFolderPath = externalPath .. "/Grabación con Plugin/"
    soundFolder = File(soundFolderPath)
    soundFiles = soundFolder.listFiles()

    if soundFiles ~= nil then
        soundFileCount = Array.getLength(soundFiles)

        if soundFileCount > 0 then
            soundFileCreationTimes = {}
            for i = 0, soundFileCount - 1 do
                soundFile = soundFiles[i]
                soundFilePath = soundFile.getAbsolutePath()

                fileName = soundFile.getName()
                creationTime = soundFile.lastModified()

                table.insert(soundFileCreationTimes, { filePath = soundFilePath, displayName = fileName, creationTime = creationTime })
            end

            table.sort(soundFileCreationTimes, function(a, b)
                return a.creationTime < b.creationTime
            end)

            for i = 1, #soundFileCreationTimes do
                soundFile = soundFileCreationTimes[i]
                table.insert(soundFilePaths, { filePath = soundFile.filePath, displayName = soundFile.displayName })
            end

            list.adapter.clear()
            for i, fileData in ipairs(soundFilePaths) do
                list.adapter.add(fileData.displayName)
            end
            list.adapter.notifyDataSetChanged()
        else
            service.asyncSpeak("Não foram encontrados arquivos de som na pasta: " .. soundFolderPath)
        end
    else
        service.asyncSpeak("Não foi possível acessar a pasta: " .. soundFolderPath)
    end
end

function renameItem(position)
    fileData = soundFilePaths[position + 1]
    file = File(fileData.filePath)
    fileName, fileExtension = string.match(fileData.displayName, "(.-)(%.%w+)$")

    renameDialog = LuaDialog(context)
    renameDialog.setTitle("Renomear Arquivo")

    input = EditText(context)
    input.setText(fileName)

    renameDialog.setView(input)

    renameDialog.setPositiveButton("Aceitar", DialogInterface.OnClickListener {
        onClick = function(dialog, which)
            newFileName = tostring(input.getText())
            newFilePath = file.getParent() .. "/" .. newFileName .. fileExtension
            newFile = File(newFilePath)

            if file.renameTo(newFile) then
                fileData.displayName = newFileName .. fileExtension
                adapterItems[position + 1] = fileData

                counterFile = File("/storage/emulated/0/orden.txt")
                counterFile.delete()
                list.adapter.clear()
                for i, fileData in ipairs(soundFilePaths) do
                    list.adapter.add(fileData.displayName)
                end
                list.adapter.notifyDataSetChanged()

                service.asyncSpeak("Arquivo renomeado com sucesso.")
                guardarOrden()
                cargarOrden()
                cargarArchivos()
            else
                service.asyncSpeak("Erro ao renomear o arquivo.")
            end

            dialog.dismiss()
        end
    })

    renameDialog.setNegativeButton("Cancelar", DialogInterface.OnClickListener {
        onClick = function(dialog, which)
            dialog.dismiss()
        end
    })

    renameDialog.show()
end

function cargarOrden()
    externalPath = Environment.getExternalStorageDirectory().getAbsolutePath()
    ordenFilePath = externalPath .. "/orden.txt"

    ordenFile = File(ordenFilePath)
    if ordenFile.exists() then
        soundFilePaths = {}

        inputStream = FileInputStream(ordenFile)
        reader = BufferedReader(InputStreamReader(inputStream))

        line = reader.readLine()
        while line ~= nil do
            filePath, displayName = line:match("([^,]+),([^,]+)")
            table.insert(soundFilePaths, { filePath = filePath, displayName = displayName })

            line = reader.readLine()
        end

        reader.close()
    end
end

cargarOrden()

adapterItems = {}
for i, fileData in ipairs(soundFilePaths) do
    table.insert(adapterItems, fileData.displayName)
end

function combineFiles2()
    combinedFileName = "arquivo_combinado"
    combinedFileExtension = ".wav"
    combinedFilePath = soundFolderPath .. combinedFileName .. combinedFileExtension

    combinedFile = io.open(combinedFilePath, "wb")

    if combinedFile then
        for i, fileData in ipairs(soundFilePaths) do
            soundFile = io.open(fileData.filePath, "rb")

            if soundFile then
                data = soundFile:read("*a")
                combinedFile:write(data)
                soundFile:close()
            else
                service.asyncSpeak("Erro ao abrir o arquivo: " .. fileData.filePath)
            end
        end

        combinedFile:close()
        service.asyncSpeak("Arquivos combinados com sucesso")

        list.adapter.clear()
        for i, fileData in ipairs(soundFilePaths) do
            list.adapter.add(fileData.displayName)
        end
        list.adapter.notifyDataSetChanged()

        guardarOrden()
        cargarOrden()
        cargarArchivos()
    else
        service.asyncSpeak("Erro ao criar o arquivo combinado.")
    end
end

function openFolder()
    intent = Intent(Intent.ACTION_VIEW)
    intent.setDataAndType(Uri.parse(soundFolderPath), "resource/folder")
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    context.startActivity(intent)
    counterFile = File("/storage/emulated/0/orden.txt")
    counterFile.delete()
    dlg.dismiss()
end

function shareFile(position)
    selectedSoundFilePath = soundFilePaths[position + 1].filePath
    service.shareFile(selectedSoundFilePath)
    guardarOrden()
    dlg.dismiss()
end

function deleteItem(position)
    fileData = soundFilePaths[position + 1]
    file = File(fileData.filePath)

    confirmationDialog = LuaDialog(context)
    confirmationDialog.setTitle("Excluir Arquivo")
    confirmationDialog.setMessage("Tem certeza de que deseja excluir este arquivo?")
    confirmationDialog.setPositiveButton("Excluir", DialogInterface.OnClickListener {
        onClick = function(dialog, which)
            file.delete()
            table.remove(soundFilePaths, position + 1)
            service.asyncSpeak("Arquivo excluído com sucesso.")

            adapter = list.adapter
            adapter.clear()
            for i, fileData in ipairs(soundFilePaths) do
                adapter.add(fileData.displayName)
            end
            adapter.notifyDataSetChanged()

            guardarOrden()
            cargarOrden()
        end
    })
    confirmationDialog.setNegativeButton("Cancelar", DialogInterface.OnClickListener {
        onClick = function(dialog, which)
            dialog.dismiss()
        end
    })
    confirmationDialog.show()
end

function deleteFiles()
    confirmationDialog = LuaDialog(context)
    confirmationDialog.setTitle("Excluir Todos os Arquivos")
    confirmationDialog.setMessage("Tem certeza de que deseja excluir todos os arquivos?")
    confirmationDialog.setPositiveButton("Excluir", DialogInterface.OnClickListener {
        onClick = function(dialog, which)
            for i, fileData in ipairs(soundFilePaths) do
                file = File(fileData.filePath)
                file.delete()
            end

            counterFile = File("/storage/emulated/0/contador.txt")
            counterFile.delete()
            counter3File = File("/storage/emulated/0/orden.txt")
            counter3File.delete()

            soundFilePaths = {}
            service.asyncSpeak("Arquivos excluídos com sucesso.")
            dlg.dismiss()
        end
    })
    confirmationDialog.setNegativeButton("Cancelar", DialogInterface.OnClickListener {
        onClick = function(dialog, which)
            dialog.dismiss()
        end
    })
    confirmationDialog.show()
end

function closeDialog()
    if isPlaying then
        mediaPlayer.stop()
        mediaPlayer.reset()
        isPlaying = false
        currentSoundFilePath = nil
    end
    guardarOrden()
    dlg.dismiss()
end

function subir(position)
    if position > 0 then
        fileData = table.remove(soundFilePaths, position + 1)
        table.insert(soundFilePaths, position, fileData)

        adapter = list.adapter
        adapter.clear()
        for i, fileData in ipairs(soundFilePaths) do
            adapter.add(fileData.displayName)
        end
        adapter.notifyDataSetChanged()

        guardarOrden()
    end
end

function bajar(position)
    if position < #soundFilePaths - 1 then
        fileData = table.remove(soundFilePaths, position + 1)
        table.insert(soundFilePaths, position + 2, fileData)

        adapter = list.adapter
        adapter.clear()
        for i, fileData in ipairs(soundFilePaths) do
            adapter.add(fileData.displayName)
        end
        adapter.notifyDataSetChanged()

        guardarOrden()
    end
end

function combineFiles()
    combinedFileName = "arquivo_combinado"
    combinedFileExtension = ".mp3"
    combinedFilePath = soundFolderPath .. combinedFileName .. combinedFileExtension

    combinedFile = io.open(combinedFilePath, "wb")

    if combinedFile then
        for i, fileData in ipairs(soundFilePaths) do
            soundFile = io.open(fileData.filePath, "rb")

            if soundFile then
                data = soundFile:read("*a")
                combinedFile:write(data)
                soundFile:close()
            else
                service.asyncSpeak("Erro ao abrir o arquivo: " .. fileData.filePath)
            end
        end

        combinedFile:close()
        service.asyncSpeak("Arquivos combinados com sucesso")

        list.adapter.clear()
        for i, fileData in ipairs(soundFilePaths) do
            list.adapter.add(fileData.displayName)
        end
        list.adapter.notifyDataSetChanged()

        guardarOrden()
        cargarOrden()
        cargarArchivos()
    else
        service.asyncSpeak("Erro ao criar o arquivo combinado.")
    end
end

function guardarOrden()
    externalPath = Environment.getExternalStorageDirectory().getAbsolutePath()
    ordenFilePath = externalPath .. "/orden.txt"

    ordenFile = File(ordenFilePath)
    if not ordenFile.exists() then
        ordenFile.createNewFile()
    end

    outputStream = FileOutputStream(ordenFile)

    for i, fileData in ipairs(soundFilePaths) do
        line = fileData.filePath .. "," .. fileData.displayName .. "\n"
        for j = 1, #line do
            outputStream.write(string.byte(line, j))
        end
    end

    outputStream.close()
end

currentMatchIndex = 1
matches = {}

function buscar(query)
    local queryLower = query:lower()
    matches = {}
    for i, item in ipairs(adapterItems) do
        local text = item
        if text:lower():find(queryLower) then
            table.insert(matches, i)
        end
    end

    if #matches > 0 then
        service.asyncSpeak("Foram encontradas " .. tostring(#matches) .. " coincidências.")
        currentMatchIndex = 1
        list.setSelection(matches[currentMatchIndex] - 1)
    else
        service.asyncSpeak("Sem resultados")
    end
end

function moveToNextMatch()
    if #matches > 0 then
        currentMatchIndex = currentMatchIndex + 1
        if currentMatchIndex > #matches then
            currentMatchIndex = 1
        end
        list.setSelection(matches[currentMatchIndex] - 1)
    else
        service.asyncSpeak("Não há resultados de busca para navegar.")
    end
end

function scrollToMatch(matchIndex)
    local y = editTexts[matchIndex].getTop()
    scrollView.post(Runnable({run=function()
        scrollView.scrollTo(0, y)
    end}))
    service.asyncSpeak("Indo para a coincidência " .. tostring(currentMatchIndex) .. " de " .. tostring(#matches))
end

function nextMatch()
    if #matches > 0 then
        currentMatchIndex = currentMatchIndex % #matches + 1
        scrollToMatch(matches[currentMatchIndex])
    else
        service.asyncSpeak("Sem resultados")
    end
end

Runnable = luajava.bindClass("java.lang.Runnable")
DelayedRunnable = Runnable {
    run = function()
        currentPosition = mediaPlayer.getCurrentPosition()
        id_startTime.setText(formatTime(currentPosition))
        id_Progress.setProgress(currentPosition)
        updateHandler.postDelayed(DelayedRunnable, 1000)
    end
}
currentPosition = 0
totalDuration = 0
updateHandler = Handler()

function formatTime(duration)
    minutes = math.floor(duration / 60000)
    seconds = math.floor((duration % 60000) / 1000)
    return string.format("%02d:%02d", minutes, seconds)
end

function stopUpdateHandler()
    updateHandler.removeCallbacksAndMessages(nil)
end

function stopPauseButtonClicked()
    if isPlaying then
        mediaPlayer.pause()
        isPlaying = false
    else
        mediaPlayer.start()
        isPlaying = true
    end
end

function playNextTrack()
    local nextPosition = currentSoundIndex + 1
    if nextPosition <= #soundFilePaths then
        local nextSoundFilePath = soundFilePaths[nextPosition].filePath
        playSound(nextSoundFilePath)
    end
end

function playPreviousTrack()
    local previousPosition = currentSoundIndex - 1
    if previousPosition >= 1 then
        local previousSoundFilePath = soundFilePaths[previousPosition].filePath
        playSound(previousSoundFilePath)
    end
end

function playSound(soundFilePath)
    if currentSoundFilePath == soundFilePath then
        mediaPlayer.stop()
        mediaPlayer.reset()
        isPlaying = false
        currentSoundFilePath = nil
        stopUpdateHandler()
        return
    end

    if isPlaying then
        mediaPlayer.stop()
        mediaPlayer.reset()
        stopUpdateHandler()
    end

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
    mediaPlayer.reset()
    mediaPlayer.setDataSource(soundFilePath)
    mediaPlayer.prepare()
    mediaPlayer.start()

    local songName = string.match(soundFilePath, ".*/(.*)")
    id_songName.text = songName
    isPlaying = true
    currentSoundFilePath = soundFilePath

    totalDuration = mediaPlayer.getDuration()
    id_endTime.setText(formatTime(totalDuration))
    id_Progress.setMax(totalDuration)

    currentPosition = mediaPlayer.getCurrentPosition()
    id_startTime.setText(formatTime(currentPosition))
    id_Progress.setProgress(currentPosition)

    id_Progress.setOnSeekBarChangeListener({
        onProgressChanged = function(seekBar, progress, fromUser)
            if fromUser then
                mediaPlayer.seekTo(progress)
                currentPosition = progress
                id_startTime.setText(formatTime(currentPosition))
            end
        end,
        onStartTrackingTouch = function(seekBar)
        end,
        onStopTrackingTouch = function(seekBar)
        end
    })

    local currentTrackIndex = nil
    for i, fileData in ipairs(soundFilePaths) do
        if fileData.filePath == soundFilePath then
            currentTrackIndex = i
            break
        end
    end

    if currentTrackIndex then
        list.setSelection(currentTrackIndex - 1)
    end

    updateHandler.postDelayed(DelayedRunnable, 1000)

    run = function()
        currentPosition = mediaPlayer.getCurrentPosition()
        id_startTime.setText(formatTime(currentPosition))
        id_Progress.setProgress(currentPosition)
        updateHandler.postDelayed(this, 1000)
    end

    for i, fileData in ipairs(soundFilePaths) do
        if fileData.filePath == soundFilePath then
            currentSoundIndex = i
            break
        end
    end

    mediaPlayer.setOnCompletionListener({
        onCompletion = function(mp)
            nextPosition = currentSoundIndex + 1
            if nextPosition <= #soundFilePaths then
                nextSoundFilePath = soundFilePaths[nextPosition].filePath
                playSound(nextSoundFilePath)
            end
        end
    })
end

layout = {
    LinearLayout,
    orientation = "vertical",
    layout_width = "match_parent",
    layout_height = "match_parent",
    backgroundColor = "#212121",
    padding = "10dp",
    {
        TextView,
        text = "Administrador de Gravações",
        textSize = "18sp",
        textColor = "#FFFFFF",
        gravity = "center",
        layout_width = "match_parent",
        padding = "16dp",
    },
    {
        TextView,
        id = "musicFileCount",
        text = "Foram encontrados " .. #soundFilePaths .. " gravações na pasta.",
        textSize = "14sp",
        textColor = "#B0BEC5",
        gravity = "center",
        layout_width = "match_parent",
        padding = "8dp",
    },
    {
        LinearLayout,
        orientation = "horizontal",
        layout_width = "match_parent",
        layout_height = "wrap_content",
        padding = "8dp",
        {
            EditText,
            id = "searchEditText",
            hint = "Buscar gravações...",
            textSize = "14sp",
            textColor = "#FFFFFF",
            hintTextColor = "#B0BEC5",
            layout_width = "0dp",
            layout_weight = "1",
            layout_height = "wrap_content",
        },
        {
            Button,
            text = "Próximo Resultado",
            textSize = "14sp",
            textColor = "#FFFFFF",
            backgroundColor = "#0288D1",
            layout_width = "wrap_content",
            layout_height = "wrap_content",
            layout_marginLeft = "8dp",
            onClick = function(view)
                moveToNextMatch()
            end,
        },
    },
    {
        ScrollView,
        layout_width = "match_parent",
        layout_height = "0dp",
        layout_weight = "1",
        {
            ListView,
            id = "list",
            fastScrollEnabled = false,
            layout_width = "match_parent",
            layout_height = "wrap_content",
            backgroundColor = "#424242",
        },
    },
    {
        CardView,
        layout_width = "match_parent",
        layout_height = "wrap_content",
        cardElevation = "4dp",
        radius = "8dp",
        backgroundColor = "#424242",
        layout_margin = "8dp",
        {
            LinearLayout,
            orientation = "vertical",
            layout_width = "match_parent",
            layout_height = "wrap_content",
            padding = "8dp",
            {
                TextView,
                id = "id_songName",
                text = "",
                textSize = "14sp",
                textColor = "#FFFFFF",
                layout_width = "match_parent",
                paddingBottom = "4dp",
            },
            {
                SeekBar,
                id = "id_Progress",
                layout_width = "match_parent",
                layout_height = "wrap_content",
            },
            {
                LinearLayout,
                orientation = "horizontal",
                layout_width = "match_parent",
                layout_height = "wrap_content",
                {
                    TextView,
                    id = "id_startTime",
                    text = "00:00",
                    textSize = "12sp",
                    textColor = "#B0BEC5",
                    layout_width = "0dp",
                    layout_weight = "1",
                },
                {
                    TextView,
                    id = "id_endTime",
                    text = "00:00",
                    textSize = "12sp",
                    textColor = "#B0BEC5",
                    layout_width = "0dp",
                    layout_weight = "1",
                    gravity = "end",
                },
            },
            {
                LinearLayout,
                orientation = "horizontal",
                layout_width = "match_parent",
                layout_height = "wrap_content",
                gravity = "center",
                paddingTop = "8dp",
                {
                    Button,
                    id = "id_previousButton",
                    text = "Anterior",
                    textSize = "14sp",
                    textColor = "#FFFFFF",
                    backgroundColor = "#0288D1",
                    layout_width = "wrap_content",
                    layout_height = "wrap_content",
                    layout_margin = "4dp",
                    onClick = "playPreviousTrack",
                },
                {
                    Button,
                    id = "id_playpauseButton",
                    text = "Tocar/Pausar",
                    textSize = "14sp",
                    textColor = "#FFFFFF",
                    backgroundColor = "#0288D1",
                    layout_width = "wrap_content",
                    layout_height = "wrap_content",
                    layout_margin = "4dp",
                    onClick = "stopPauseButtonClicked",
                },
                {
                    Button,
                    id = "id_nextButton",
                    text = "Próxima",
                    textSize = "14sp",
                    textColor = "#FFFFFF",
                    backgroundColor = "#0288D1",
                    layout_width = "wrap_content",
                    layout_height = "wrap_content",
                    layout_margin = "4dp",
                    onClick = "playNextTrack",
                },
            },
        },
    },
    {
        LinearLayout,
        orientation = "vertical",
        layout_width = "match_parent",
        layout_height = "wrap_content",
        padding = "8dp",
        {
            Button,
            id = "btnCombineFiles",
            text = "Combinar em MP3",
            textSize = "14sp",
            textColor = "#FFFFFF",
            backgroundColor = "#FF5722",
            layout_width = "match_parent",
            layout_height = "wrap_content",
            layout_marginBottom = "8dp",
            onClick = "combineFiles",
        },
        {
            Button,
            id = "btnCombineFiles2",
            text = "Combinar em WAV",
            textSize = "14sp",
            textColor = "#FFFFFF",
            backgroundColor = "#FF5722",
            layout_width = "match_parent",
            layout_height = "wrap_content",
            layout_marginBottom = "8dp",
            onClick = "combineFiles2",
        },
        {
            Button,
            id = "btnOpenFolder",
            text = "Abrir Pasta",
            textSize = "14sp",
            textColor = "#FFFFFF",
            backgroundColor = "#4CAF50",
            layout_width = "match_parent",
            layout_height = "wrap_content",
            layout_marginBottom = "8dp",
            onClick = "openFolder",
        },
        {
            Button,
            id = "btnDeleteItem",
            text = "Excluir Todos os Arquivos",
            textSize = "14sp",
            textColor = "#FFFFFF",
            backgroundColor = "#D32F2F",
            layout_width = "match_parent",
            layout_height = "wrap_content",
            layout_marginBottom = "8dp",
            onClick = "deleteFiles",
        },
        {
            Button,
            id = "btncloseDialog",
            text = "Salvar e Fechar",
            textSize = "14sp",
            textColor = "#FFFFFF",
            backgroundColor = "#0288D1",
            layout_width = "match_parent",
            layout_height = "wrap_content",
            onClick = "closeDialog",
        },
    },
}

mediaPlayer = MediaPlayer()
isPlaying = false
currentSoundFilePath = nil

dlg = LuaDialog(service)
dlg.View = loadlayout(layout)

adapterItems = {}
for i, fileData in ipairs(soundFilePaths) do
    table.insert(adapterItems, fileData.displayName)
end

list.adapter = ArrayAdapter(service, android.R.layout.simple_list_item_1, adapterItems)

-- Configuração do divider programaticamente
list.setDivider(ColorDrawable(Color.parseColor("#B0BEC5")))
list.setDividerHeight(1)

dlg.show()
searchEditText.addTextChangedListener({
    onTextChanged = function(s, start, before, count)
        buscar(s.toString())
    end
})

list.onItemClick = function(l, v, position, id)
    vibrator.vibrate(100)
    selectedSoundFilePath = soundFilePaths[position + 1].filePath
    playSound(selectedSoundFilePath)
end

list.onItemLongClick = function(l, v, position, id)
    isLongPress = true
    vibrator.vibrate(100)
    options = {"Excluir", "Compartilhar", "Renomear", "Subir", "Descer"}

    dialog = LuaDialog(context)
    dialog.setTitle("Opções")

    layout = {
        LinearLayout,
        orientation = "vertical",
        {
            Button,
            text = options[1],
            layout_width = "match_parent",
            onClick = function(view)
                deleteItem(position)
                dialog.dismiss()
            end
        },
        {
            Button,
            text = options[2],
            layout_width = "match_parent",
            onClick = function(view)
                shareFile(position)
                dialog.dismiss()
            end
        },
        {
            Button,
            text = options[3],
            layout_width = "match_parent",
            onClick = function(view)
                renameItem(position)
                dialog.dismiss()
            end
        },
        {
            Button,
            text = options[4],
            layout_width = "match_parent",
            onClick = function(view)
                subir(position)
                dialog.dismiss()
            end
        },
        {
            Button,
            text = options[5],
            layout_width = "match_parent",
            onClick = function(view)
                bajar(position)
                dialog.dismiss()
            end
        }
    }

    contentView = loadlayout(layout)
    dialog.setView(contentView)
    dialog.setCancelable(true)
    dialog.show()

    return true
end